package com.stylefeng.guns.modular.huamao.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Component
public class CacheUtil {


    @Autowired
    private RedisTemplate redisTemplate;


    public void set(final String key, Object value) {
        try {
            set(key,value,60 * 60 * 24 * 7L);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public void set(String key, Object value, Long time) {
        redisTemplate.opsForValue().set(key, value);
        if (time > 0) {
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }

    /**
     * 判断是否是key值
     *
     * @param key
     * @return
     */
    public Boolean isKeyInCache(final String key) {
        return redisTemplate.hasKey(key);
    }

    public Object get(final String key) {
        Object result = null;
        result = redisTemplate.boundValueOps(key).get();
        if (result == null) {
            return null;
        }
        set(key, result);
        return result;
    }

    public Object simpleGet(final String key){
        Object result = null;
        result = redisTemplate.boundValueOps(key).get();
        if (result == null) {
            return null;
        }
        return result;
    }


    public void remove(String key) {
        if (isKeyInCache(key)) {
            redisTemplate.delete(key);
        }
        ;
    }

    public void update(String key, Object value) {
        Element element = new Element(key, value);
        set(key, value);
    }

}
